package com.sunday.common.sharding.sphere.jdbc.study.base.sync;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: zsy
 * @Create: 2023/4/4 14:58
 */
public class SynchronizeAndClassLock3 {

    /**
     * synchronized分别修饰同一个静态对象时互斥
     *
     * 【结论】synchronized分别修饰同一个类的静态对象时互斥,反过来，如果是修饰不同的静态对象，
     * 肯定不会互斥，比如将上面代码中标【1】和【2】的synchronized代码结合使用。
     */
    public static void main(String[] args) throws Exception {

        new Thread(() -> {
            new RunObject1().test1();
        }).start();

        new Thread(() -> {
            new RunObject2().test2();
        }).start();
    }
}

class RunObject1 {
    public static void test1(){
        // 【1】synchronized (StaticLock2.staticLock1) {
        synchronized (StaticLock2.staticLock) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {}
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }
}


class RunObject2 {
    public static void test2() {
        // 【2】synchronized (StaticLock2.staticLock2) {
        synchronized (StaticLock2.staticLock) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {}
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }
}

class StaticLock2 {
    public static Object staticLock = new Object();
}